package com.huilian.iotbox.admin.quartz.config;

import com.huilian.iotbox.admin.quartz.JobFactory;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertiesFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Properties;

/**
 * @author: zhangyingjie
 * @description:
 * @date: 2018/11/17 15:55
 */
@Slf4j
@Configuration
@EnableScheduling
public class SchedulerConfig {


    @Resource
    JobFactory jobFactory;

    @Value("${spring.profiles.active}")
    private String profiles;


    @Bean(name = "SchedulerFactory")
    public SchedulerFactoryBean schedulerFactoryBean() throws IOException {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();

        //用于quartz集群,QuartzScheduler 启动时更新己存在的Job，这样就不用每次修改targetObject后删除qrtz_job_details表对应记录了
        //factory.setOverwriteExistingJobs(true);

        //QuartzScheduler 延时启动，应用启动完10秒后 QuartzScheduler 再启动
        factory.setStartupDelay(10);

        factory.setQuartzProperties(quartzProperties());  //作业及数据源配置信息

        // 自定义Job Factory，用于Spring注入  service,bin等
        factory.setJobFactory(jobFactory);

        return factory;
    }

    @Bean
    public Properties quartzProperties() throws IOException {
        PropertiesFactoryBean propertiesFactoryBean = new PropertiesFactoryBean();
//        if (profiles.startsWith("dev")) {
//            log.info("---------------------定时任务为生产环境！---------------------");
//            propertiesFactoryBean.setLocation(new ClassPathResource("/quartz-" + profiles + ".properties"));
//        } else {
//            log.info("---------------------定时任务为测试环境！---------------------");
//            propertiesFactoryBean.setLocation(new ClassPathResource("/quartz-test.properties"));
//        }

        log.info("---------------------定时任务为{}环境！---------------------", profiles);
        propertiesFactoryBean.setLocation(new ClassPathResource("/quartz-" + profiles + ".properties"));

        //在quartz.properties中的属性被读取并注入后再初始化对象
        propertiesFactoryBean.afterPropertiesSet();
        return propertiesFactoryBean.getObject();
    }

    /**
     * quartz初始化监听器
     */
/*    @Bean
    public QuartzInitializerListener executorListener() {
       return new QuartzInitializerListener();
    }*/

    /**
     * 通过SchedulerFactoryBean获取Scheduler的实例
     *
     * @return
     * @throws IOException
     */
    @Bean(name = "Scheduler")
    public Scheduler scheduler() throws IOException {
        return schedulerFactoryBean().getScheduler();
    }


}